package com.example.weatherapp1.domain.usecase

import com.example.weatherapp1.data.model.City
import com.example.weatherapp1.data.model.WeatherResponse
import com.example.weatherapp1.data.repository.WeatherRepository
import com.example.weatherapp1.domain.service.LocationService
import com.example.weatherapp1.domain.service.WeatherService
import javax.inject.Inject


class GetWeatherForCurrentLocationUseCase @Inject constructor(
    private val locationService: LocationService,
    private val weatherRepository: WeatherRepository,
    private val weatherService: WeatherService
) {
    suspend operator fun invoke(): WeatherResponse? {
        // 检查是否有定位权限
        if (!locationService.hasLocationPermission()) {
            return null
        }

        // 获取当前位置
        val location = locationService.getLastKnownLocation()
            ?: return null

        // 检查是否已有当前位置城市
        var currentCity = weatherRepository.getCurrentLocationCity()

        // 如果没有，创建一个新的城市记录
        if (currentCity == null) {
            currentCity = City(
                name = "当前位置",
                latitude = location.latitude,
                longitude = location.longitude,
                isCurrentLocation = true
            )
            weatherRepository.addCity(currentCity)
            // 由于插入后ID会自动生成，需要重新获取
            currentCity = weatherRepository.getCurrentLocationCity()
                ?: return null
        } else {
            // 更新经纬度
            currentCity = currentCity.copy(
                latitude = location.latitude,
                longitude = location.longitude
            )
            weatherRepository.updateCity(currentCity)
        }

        // 获取并保存天气数据
        return weatherService.fetchAndSaveWeather(currentCity)
    }
}
